package zl.Dao;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.stereotype.Repository;
import zl.Entity.Animal;
import zl.Util.HibernateUtil;

import java.util.List;

@Repository
public class AnimalDao {
    public List<Animal> selectAll(){
        Session session= HibernateUtil.openSession();
        Transaction tx=session.beginTransaction();
        String hql="from Animal";
        List<Animal> list=session.createQuery(hql, Animal.class).list();
        tx.commit();
        HibernateUtil.closeSession();
        return list;
    }

    public void editUpdate(Animal animal){
        Session session=HibernateUtil.openSession();
        Transaction tx=session.beginTransaction();
        session.update(animal);
        tx.commit();
        HibernateUtil.closeSession();
    }

    public void deleteById(String AId){
        Session session=HibernateUtil.openSession();
        Transaction tx=session.beginTransaction();
        String hql="from Animal where AId = ?1";
        List<Animal> animals=session.createQuery(hql,Animal.class).setParameter(1,AId).list();
        session.delete(animals.get(0));
        tx.commit();
        HibernateUtil.closeSession();
    }

    public Animal selectByAId(String AId){
        Session session=HibernateUtil.openSession();
        Transaction tx=session.beginTransaction();
        String hql="from Animal where AId = ?1";
        List<Animal> animals=session.createQuery(hql,Animal.class).setParameter(1,AId).list();
        tx.commit();
        HibernateUtil.closeSession();
        return animals.size()>0?animals.get(0):null;
    }

    public void save(Animal animal){
        Session session=HibernateUtil.openSession();
        Transaction tx=session.beginTransaction();
        session.save(animal);
        tx.commit();
        HibernateUtil.closeSession();
    }
}
